'use strict';

const { logger } = require('ee-core/log');
const { createSoundsPackCache, isSoundsPackCache, isSoundsPack, convertToOgg, toSoundsPackZip,openExeFolder } = require('../utils/index')

/**
 * 音乐包控制器
 * @class
 */
class SoundsPackController {

  /**
   * 创建音频包
   * @param args 前端传的参数
   * @param event - ipc通信时才有值
   */
  async create(args, event) {
    // 参数校验
    if (!args?.name) {
      return {
        status: 404,
        msg: '参数为空或缺少name字段'
      }
    }

    // 检查音频包是否已存在
    const isPackExists = isSoundsPackCache(args.name) || isSoundsPack(args.name);
    if (isPackExists) {
      return {
        status: 201,
        msg: '已存在同名音频包'
      }
    }

    try {
      // 创建音频包
      const res = createSoundsPackCache(args);
      logger.info('[soundsPack] create success:', args.name);

      return {
        status: 200,
        data: res
      }
    } catch (error) {
      logger.error('[soundsPack] create failed:', error);
      return {
        status: 500,
        msg: '创建音频包失败'
      }
    }
  }

  /**
 * 覆盖创建音频包
 * @param args 前端传的参数
 * @param event - ipc通信时才有值
 */
  async Ycreate(args, event) {
    if (!args) {
      return {
        status: 404,
        msg: '参数为空'
      }
    }
    const res = createSoundsPackCache(args)
    logger.info('[soundsPack] create', args.name)
    return {
      status: 200,
      data: res
    }
  }

  /**
 * 将音频文件转换为OGG格式并添加到音频包中
 * @param args 前端传的参数
 * @param event - ipc通信时才有值
 */
  async toOgg(args, event) {
    // 参数校验
    if (!args?.name && !args?.path && !args?.value) {
      return {
        status: 404,
        msg: '参数为空，缺少name,path,value字段'
      }
    }

    try {
      // 转换音频
      const res = await convertToOgg(args.name, args.path, args.value);
      logger.info('[soundsPack] toOgg success:', JSON.stringify(args));

      return {
        status: 200,
        data: res
      }
    } catch (error) {
      logger.error('[soundsPack] toOgg failed:', error);
      return {
        status: 500,
        msg: '转换音频失败'
      }
    }
  }

  /**
 * 打包
 * @param args 前端传的参数
 * @param event - ipc通信时才有值
 */
  async toSoundsPack(args, event) {
    // 参数校验
    if (!args?.name) {
      return {
        status: 404,
        msg: '参数为空，缺少name字段'
      }
    }

    try {
      // 转换音频
      const res = await toSoundsPackZip(args.name);
      logger.info('[soundsPack] toSoundsPack success:', res);

      return {
        status: 200,
        data: res
      }
    } catch (error) {
      logger.error('[soundsPack] toSoundsPack failed:', error);
      return {
        status: 500,
        msg: '转换音频失败'
      }
    }
  }

  /**
* 打开文件夹
* @param args 前端传的参数
* @param event - ipc通信时才有值
*/
  async openFolder(args, event) {
    // 参数校验
    openExeFolder();
  }

}
SoundsPackController.toString = () => '[class SoundsPackController]';

module.exports = SoundsPackController; 